<script setup>
	import {ref,reactive} from 'vue'
	import userApi from '@/apis/user'
	import {useUserStore} from '@/stores/user'
	import {onLoad} from '@dcloudio/uni-app'
	// 调用读取数据
	const userStore = useUserStore()
	// 获取表单组件
	const loginForm = ref()
	// 定义表单响应式数据
	const formData = reactive({
		account:'',
		password:''
	})
	// 定义表单规则
	const formRules = reactive({
		account:{
			rules:[
				{required:true,errorMessage:'请输入登录账号'},
				{pattern:'^[a-zA-Z0-9]{6,8}$',errorMessage:'登录账号格式不正确'}
			]
		},
		password:{
			rules:[
				{required:true,errorMessage:'请输入登录密码'},
				{pattern:'^\\d{6}$',errorMessage:'登录密码格式不正确'}
			]
		}
	})
	// 表单提交
	const onSubmitForm = async () => {
		try{
			await loginForm.value.validate()
			// 调用登录接口
			const {code,data} = await userApi.login(formData)
			if(code!==200) return uni.utils.toast('登录失败')
			userStore.token = data
			// 跳转回之前的页面
			uni[routeType.value]({	
				url:redirectURL.value
			})
		} catch(err) {
			console.log(err);
		}
	}
	// 获取页面路径
	const redirectURL = ref('')
	// 获取页面路径类型
	const routeType = ref('')
	onLoad((query)=>{
		redirectURL.value = query.redirectURL
		routeType.value = query.routeType
	})
</script>

<template>
	<uni-forms class="login-form" ref="loginForm" :rules="formRules" :model="formData">
		<uni-forms-item name="account">
			<input
				v-model="formData.account"
				type="text"
				placeholder="请输入账号"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<input
				v-model="formData.password"
				type="text"
				placeholder="请输入密码"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<button class="submit-button" @click="onSubmitForm">登录</button>
	</uni-forms>
</template>

<style lang="scss" scoped>
	@import './styles.scss';
</style>
